/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This code is derived from the project ojoverse (2008, same author)
 * under the license GPL2. See <http://www.gnu.org/licenses/>.
 */

package org.ix.net;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ix.data.entities.User;

/**
 * An abstract Servlet without a default output stream.
 * Useful for a) operations that doesn't need a response; b) use of others output stream (eg. ServletOutputStream for file download)
 * @author
 */
public abstract class BaseMuteServlet extends BaseServlet {

    protected void process(HttpServletRequest req, HttpServletResponse res) {
        String address = req.getServerName();   //req.getRemoteAddr();
        if (address == null || !address.equals("localhost")) {
            User user = (User) req.getSession().getAttribute("user");
            if (user == null || !user.isLogged()) {
                String servletPath = req.getServletPath();
                if (servletPath != null && !servletPath.equals("/login")) {
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login");
                    if (dispatcher != null) {
                        try {
                            dispatcher.forward(req, res);
                        } catch (Exception exc) {
                            return;
                        }
                    }
                }
            }
        }

        serve(req, res);
    }

    protected abstract void serve(HttpServletRequest request, HttpServletResponse response);
}
